################################################################################ 
#
# Counterspeech encouraging users to adopt the perspective of minority 
# groups reduces hate speech and its amplification on social media
#
# Figure 3
#
################################################################################ 


rm(list = ls())

# Set to save results
setsave = T

################################################################################ 
#  LIBRARIES
################################################################################ 

library(dplyr)
library(ggplot2)
library(readr)
library(doBy)
library(data.table)
library(RColorBrewer)


################################################################################ 
#   DATA AND FOLDER
################################################################################ 

wd = ''
wd_res = paste0(wd, '/results')
wd_data =  paste0(wd, '/data')


data = read.csv(paste0(wd_data, '/dataset_analysis.csv'))
data = data[!(data$user_deleted == "yes"),]

# Re-code NAs to 0 when the original tweet is deleted
data$n_favorites_to_orig_tweet[data$orig_tweet_deleted ==1] = 0
data$n_retweets_to_orig_tweet[data$orig_tweet_deleted==1] = 0

# No impact on result, just a trick for modeling tables
data$reply_count[data$control=='yes'] = 0

################################################################################ 
#   VARIABLES
################################################################################


outvars = c('n_favorites_to_orig_tweet', 'n_retweets_to_orig_tweet',
             'reply_count')
outvars_name = c('No. of likes received\nby xenophobic tweet', 'No. of retweets\nof xenophobic tweet',
                 "No. of user's replies\nto counterspeech tweet")

treatments = c('empathy', 'traditional', 'analogical', 'getting', 'disapproval')
treatments_lab = c( 'Perspective (all)', 
                    'Traditional\nPerspective Taking',
                    'Analogical\nPerspective Taking',
                    'Perspective\nGetting', 
                    'Disapproval')

################################################################################ 
#   Scale variables
################################################################################ 

std <- function(x) sd(x, na.rm=TRUE)/sqrt(length(x))
mean <- function(x)base::mean(x, na.rm=TRUE)

################################################################################ 
#   Create Group Means and SD
################################################################################ 

temp = data[c(outvars, 'group_number', 'group_name')]



# Means
container1 = summaryBy(as.formula(paste0(paste0(outvars, collapse='+'), '~ group_num + group_name')),FUN=c(mean), data=temp)
colnames(container1) = c('treat', outvars)
container1 <- melt(setDT(container1), id.vars = c("treat"), variable.name = "yvar")
colnames(container1) = c('treat', 'yvar', 'mean')

# STD
container2 = summaryBy(as.formula(paste0(paste0(outvars, collapse='+'), '~ group_num + group_name')), FUN=c(std), data=temp)
colnames(container2) = c('treat', outvars)
container2 <- melt(setDT(container2), id.vars = c("treat"), variable.name = "yvar")
colnames(container2) = c('treat', 'yvar', 'sd')

# empathy
temp$group_name[temp$group_name %in% c('getting', 'traditional', 'analogical')] = 'empathy'
container3 = summaryBy(as.formula(paste0(paste0(outvars, collapse='+'), '~ group_num + group_name')), FUN=c(mean), data=temp)
container3 = container3[container3$group_name=='empathy',]
colnames(container3) = c('treat', outvars)
container3 <- melt(setDT(container3), id.vars = c("treat"), variable.name = "yvar")
colnames(container3) = c('treat', 'yvar', 'mean')

# empathy
container4 = summaryBy(as.formula(paste0(paste0(outvars, collapse='+'), '~ group_num + group_name')), FUN=c(std), data=temp)
container4 = container4[container4$group_name=='empathy',]
colnames(container4) = c('treat', outvars)
container4 <- melt(setDT(container4), id.vars = c("treat"), variable.name = "yvar")
colnames(container4) = c('treat', 'yvar', 'sd')
container3 = merge(container3, container4, by=c('treat', 'yvar'))

container = merge(container1, container2, by=c('treat', 'yvar'))
container = rbind(container, container3)
container = container[!which(is.na(container$mean)),]



# Macrogroups
container$macrogroups = ''
container$macrogroups = ifelse(container$treat %in% c('empathy', 'disapproval', 'control'), 'Perspective vs Disapproval', container$macrogroups)
container$macrogroups = ifelse(container$treat %in% c('analogical', 'traditional', 'getting'), 'Perspective Treatments', container$macrogroups)
container$macrogroups.f  = factor(container$macrogroups,
                             levels = c("Control","Perspective vs Disapproval", "Perspective Treatments"))

# Clean var names
container$yvar_name = ''
for (var in 1:length(outvars)){
  container$yvar_name[container$yvar== outvars[var]]  = outvars_name[var]
}
container$yvar_name.f  = factor(container$yvar_name,
                                levels = outvars_name)

container$treatments_lab = 'Control'
for (var in 1:length(treatments)){
  container$treatments_lab[container$treat== treatments[var]]  = treatments_lab[var]
}




container$treatments_lab.f  = factor(container$treatments_lab,
                                     levels = c("Control","Disapproval", "Perspective (all)",
                                                "Traditional\nPerspective Taking",
                                                'Analogical\nPerspective Taking', 
                                                'Perspective\nGetting'))


################################################################################ 
#   Plot
################################################################################ 

container = container[!which(container$yvar %in% c("n_favorites_to_treat_tweet", "n_retweets_to_treat_tweet")),]


my_colors <- RColorBrewer::brewer.pal(4, "Blues")[2:4]

ggplot(container, aes(x=macrogroups.f, y=mean, fill=treatments_lab.f)) +
  geom_bar(stat="identity", width = .8, position=position_dodge2()) +
  facet_wrap(~yvar_name.f, scales = "free") +
  geom_errorbar(aes(ymin=mean-sd*1.96, ymax=mean+sd*1.96), position=position_dodge(0.8), colour="grey", alpha=0.7, size=.5,  width = .5) +
  geom_text(aes(label=round(mean, 3)), vjust=-.3, color="black", position=position_dodge2(0.8), size=5)+
  xlab("") + ylab("") + guides(fill=guide_legend(title="")) +
  scale_fill_manual(values=c("#999999", "darkgoldenrod2",
                             'blue4', my_colors)) +
  theme_bw() +
  theme(text = element_text(size=18),
        axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        legend.text=element_text(size=18),
        legend.position = "bottom",
        legend.title = element_blank(),
        strip.text = element_text(size = 18)) + 
  guides(fill = guide_legend(nrow = 1))

# Save
if (setsave){ggsave(paste0(wd_res, '/figures/fig3.pdf'),  width=15, height=8)}else{print(gg1)}


